<template>
  <div class="version-manage">
    <!-- 左侧表格区域 -->
    <div class="left-panel">
      <div class="panel-header">
        <h3>版本管理</h3>
        <div class="header-actions">
          <el-button 
            type="danger" 
            size="small" 
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleAddVersion"
          >
            增加版本
          </el-button>
          <el-input
            v-model="searchQuery"
            placeholder="搜索"
            prefix-icon="el-icon-search"
            size="small"
            style="width: 200px;"
            @input="handleSearch"
          />
        </div>
      </div>
      
      <div class="table-container">
        <el-table
          :data="paginatedVersionList"
          v-loading="loading"
          style="width: 100%"
          :height="'calc(100vh - 120px)'"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="versionName" label="版本名" min-width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.versionName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="versionNumber" label="版本号" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.versionNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.remark || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="category" label="分类" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.category === 'frontend' ? '前端' : '后端' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" align="center" fixed="right">
            <template slot-scope="scope">
              <div style="display: flex; gap: 8px;">
                <el-button type="primary" size="small" @click="handleDownload(scope.row)">下载</el-button>
                <el-button type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <div class="pagination-info">
          <span>共 {{ totalItems }} 条</span>
        </div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="sizes, prev, pager, next, jumper"
          :total="totalItems"
          background
        >
        </el-pagination>
      </div>
    </div>



    <!-- 增加/上传对话框 -->
    <el-dialog
      :title="uploadDialogTitle"
      :visible.sync="uploadDialogVisible"
      width="500px"
      @close="resetUploadForm"
    >
      <el-form :model="uploadForm" label-width="80px">
        <el-form-item label="名称" required>
          <el-input v-model="uploadForm.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="版本号" required>
          <el-input v-model="uploadForm.version" placeholder="请输入版本号"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="uploadForm.remark" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item label="分类" required>
          <el-radio-group v-model="uploadForm.category">
            <el-radio label="frontend">前端</el-radio>
            <el-radio label="backend">后端</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label-width="0" style="margin-bottom: 24px;">
          <div style="display: flex; align-items: center; gap: 32px;">
            <div style="display: flex; align-items: center;">
              <span style="color: #f56c6c; margin-right: 4px;">*</span>
              <span style="width: 80px; display: inline-block; text-align: right;">简易版文件</span>
              <el-upload
                ref="simpleUpload"
                :auto-upload="false"
                :file-list="uploadForm.simpleFileList"
                :on-change="handleSimpleFileChange"
                :on-remove="handleSimpleFileRemove"
                action="#"
              >
                <el-button size="small" type="primary">选择简易版文件</el-button>
              </el-upload>
            </div>
            <div style="display: flex; align-items: center;">
              <span style="color: #f56c6c; margin-right: 4px;">*</span>
              <span style="width: 80px; display: inline-block; text-align: right;">完整版文件</span>
              <el-upload
                ref="fullUpload"
                :auto-upload="false"
                :file-list="uploadForm.fullFileList"
                :on-change="handleFullFileChange"
                :on-remove="handleFullFileRemove"
                action="#"
              >
                <el-button size="small" type="primary">选择完整版文件</el-button>
              </el-upload>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUpload" :loading="uploading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑版本"
      :visible.sync="editDialogVisible"
      width="500px"
      @close="resetEditForm"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="名称" required>
          <el-input v-model="editForm.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="版本号" required>
          <el-input v-model="editForm.version" placeholder="请输入版本号"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.remark" type="textarea" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item label="分类" required>
          <el-radio-group v-model="editForm.category">
            <el-radio label="frontend">前端</el-radio>
            <el-radio label="backend">后端</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'VersionManage',
  data() {
    return {
      searchQuery: '',
      selectedRows: [],
      // 分页相关
      currentPage: 1,
      pageSize: 10,

      uploadDialogVisible: false,
      uploadDialogTitle: '',
      uploadType: '', // 'version' 或 'baseline'
      uploadForm: {
        name: '',
        version: '',
        remark: '',
        fileList: [],
        category: 'frontend',
        simpleFileList: [],
        fullFileList: []
      },
      uploading: false,
      editDialogVisible: false,
      editForm: {
        name: '',
        version: '',
        remark: '',
        category: 'frontend'
      },
      editRow: null,
      // 模拟数据
      mockVersionList: [
        {
          id: 1,
          versionName: 'v1.0.0',
          versionNumber: '1.0.0',
          remark: '初始版本',
          createTime: '2024-04-15 10:00:00',
          category: 'frontend',
          simpleFileName: 'simple_v1.0.0.zip',
          fullFileName: 'full_v1.0.0.zip'
        },
        {
          id: 2,
          versionName: 'v1.1.0',
          versionNumber: '1.1.0',
          remark: '功能更新',
          createTime: '2024-04-16 14:30:00',
          category: 'frontend',
          simpleFileName: 'simple_v1.1.0.zip',
          fullFileName: 'full_v1.1.0.zip'
        },
        {
          id: 3,
          versionName: 'v1.2.0',
          versionNumber: '1.2.0',
          remark: 'Bug修复和性能优化',
          createTime: '2024-04-17 09:15:00',
          category: 'frontend',
          simpleFileName: 'simple_v1.2.0.zip',
          fullFileName: 'full_v1.2.0.zip'
        },
        {
          id: 4,
          versionName: 'v1.3.0',
          versionNumber: '1.3.0',
          remark: '新增功能模块',
          createTime: '2024-04-18 11:20:00',
          category: 'frontend',
          simpleFileName: 'simple_v1.3.0.zip',
          fullFileName: 'full_v1.3.0.zip'
        },
        {
          id: 5,
          versionName: 'v1.4.0',
          versionNumber: '1.4.0',
          remark: '界面优化',
          createTime: '2024-04-19 15:45:00',
          category: 'frontend',
          simpleFileName: 'simple_v1.4.0.zip',
          fullFileName: 'full_v1.4.0.zip'
        },
        {
          id: 6,
          versionName: 'v1.5.0',
          versionNumber: '1.5.0',
          remark: '安全性增强',
          createTime: '2024-04-20 09:30:00',
          category: 'frontend',
          simpleFileName: 'simple_v1.5.0.zip',
          fullFileName: 'full_v1.5.0.zip'
        },
        {
          id: 7,
          versionName: 'v2.0.0',
          versionNumber: '2.0.0',
          remark: '重大版本更新',
          createTime: '2024-04-21 16:00:00',
          category: 'frontend',
          simpleFileName: 'simple_v2.0.0.zip',
          fullFileName: 'full_v2.0.0.zip'
        },
        {
          id: 8,
          versionName: 'v2.1.0',
          versionNumber: '2.1.0',
          remark: '性能优化',
          createTime: '2024-04-22 10:15:00',
          category: 'frontend',
          simpleFileName: 'simple_v2.1.0.zip',
          fullFileName: 'full_v2.1.0.zip'
        }
      ]
    }
  },
  computed: {
    ...mapGetters('project', ['versionList', 'loading', 'total']),
    filteredVersionList() {
      return this.versionList
    },
    paginatedVersionList() {
      return this.versionList
    },
    totalItems() {
      return this.total
    }
  },
  mounted() {
    this.loadVersionList()
  },
  methods: {
    ...mapActions('project', [
      'getVersionList', 
      'uploadVersion', 
      'updateVersion', 
      'deleteVersion', 
      'batchDeleteVersions'
    ]),
    
    async loadVersionList() {
      try {
        await this.getVersionList({
          page: this.currentPage,
          pageSize: this.pageSize,
          search: this.searchQuery
        })
      } catch (error) {
        this.$message.error('加载版本列表失败')
      }
    },
    
    handleSearch() {
      this.currentPage = 1
      this.loadVersionList()
    },
    
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadVersionList()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadVersionList()
    },
    
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    
    handleAddVersion() {
      this.uploadDialogTitle = '增加版本'
      this.uploadType = 'version'
      this.uploadDialogVisible = true
    },
    
    async handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的版本')
        return
      }
      
      try {
        await this.$confirm(`确定删除选中的 ${this.selectedRows.length} 个版本吗？`, '批量删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const selectedIds = this.selectedRows.map(row => row.id)
        await this.batchDeleteVersions(selectedIds)
        this.$message.success('批量删除成功')
        this.selectedRows = []
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('批量删除失败')
        }
      }
    },
    
    handleFileChange(file, fileList) {
      this.uploadForm.fileList = fileList
    },
    
    handleFileRemove(file, fileList) {
      this.uploadForm.fileList = fileList
    },
    
    async confirmUpload() {
      if (!this.uploadForm.name || !this.uploadForm.version || 
          !this.uploadForm.simpleFileList.length || !this.uploadForm.fullFileList.length) {
        this.$message.warning('请填写完整信息并选择文件')
        return
      }
      
      this.uploading = true
      try {
        const formData = new FormData()
        formData.append('name', this.uploadForm.name)
        formData.append('version', this.uploadForm.version)
        formData.append('remark', this.uploadForm.remark)
        formData.append('category', this.uploadForm.category)
        formData.append('simpleFile', this.uploadForm.simpleFileList[0].raw)
        formData.append('fullFile', this.uploadForm.fullFileList[0].raw)
        
        await this.uploadVersion(formData)
        this.$message.success('上传成功')
        this.uploadDialogVisible = false
        this.resetUploadForm()
      } catch (error) {
        this.$message.error('上传失败')
      } finally {
        this.uploading = false
      }
    },
    
    resetUploadForm() {
      this.uploadForm = {
        name: '',
        version: '',
        remark: '',
        fileList: [],
        category: 'frontend',
        simpleFileList: [],
        fullFileList: []
      }
    },
    
    async handleDownload(row) {
      try {
        // 下载简易版
        window.open(`/api/versions/${row.id}/download?type=simple`, '_blank')
        // 下载完整版
        window.open(`/api/versions/${row.id}/download?type=full`, '_blank')
      } catch (error) {
        this.$message.error('下载失败')
      }
    },
    
    async handleDelete(row) {
      try {
        await this.$confirm(`确定删除版本 ${row.versionName} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await this.deleteVersion(row.id)
        this.$message.success('删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    
    handleEdit(row) {
      this.editDialogVisible = true
      this.editForm = {
        name: row.versionName,
        version: row.versionNumber,
        remark: row.remark,
        category: row.category
      }
      this.editRow = row
    },
    
    async confirmEdit() {
      if (!this.editForm.name || !this.editForm.version) {
        this.$message.warning('请填写完整信息')
        return
      }
      
      try {
        await this.updateVersion({
          id: this.editRow.id,
          data: {
            name: this.editForm.name,
            version: this.editForm.version,
            remark: this.editForm.remark,
            category: this.editForm.category
          }
        })
        this.$message.success('编辑成功')
        this.editDialogVisible = false
        this.resetEditForm()
      } catch (error) {
        this.$message.error('编辑失败')
      }
    },
    
    resetEditForm() {
      this.editForm = {
        name: '',
        version: '',
        remark: '',
        category: 'frontend'
      }
    },
    
    handleSimpleFileChange(file, fileList) {
      this.uploadForm.simpleFileList = fileList
    },
    
    handleSimpleFileRemove(file, fileList) {
      this.uploadForm.simpleFileList = fileList
    },
    
    handleFullFileChange(file, fileList) {
      this.uploadForm.fullFileList = fileList
    },
    
    handleFullFileRemove(file, fileList) {
      this.uploadForm.fullFileList = fileList
    }
  }
}
</script>

<style scoped>
.version-manage {
  height: calc(100vh - 120px);
  padding: 16px;
}

.left-panel {
  width: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-container {
  flex: 1;
  padding: 0 20px;
  overflow: hidden;
  height: calc(100vh - 120px);
  min-height: 400px;
  display: flex;
  flex-direction: column;
}

.table-container .el-table {
  flex: 1 1 auto;
  min-height: 0;
}

.table-container .el-table__body-wrapper {
  max-height: 100%;
  min-height: 200px;
  overflow-y: auto !important;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  background: #fff;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  border: 1px solid #ebeef5;
}

.el-form-item {
  margin-bottom: 16px;
}
</style>